package cn.wit.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;

public class DemoRandomAccessFile {
	
	@Test
	public void test() {
		
		String source = "C:\\Users\\16604\\Pictures\\Saved Pictures\\下载.jpg";
		
		String target = "C:\\Users\\16604\\Pictures\\Saved Pictures\\copy.jpg";
		
		copy(source,target);
		
	}
	
	@Test
	public void copyRemain() {
		
		String source = "C:\\Users\\16604\\Pictures\\Saved Pictures\\下载.jpg";
		
		String target = "C:\\Users\\16604\\Pictures\\Saved Pictures\\copy.jpg";
		
		try(
				RandomAccessFile raf = new RandomAccessFile(source, "r");
				FileOutputStream fo = new FileOutputStream(target);
		) {
			long filepointer = raf.getFilePointer();//获取文件指针
			
			File f = new File(target);//获取文件已经复制得地址
			
			raf.seek(f.length());//移动文件指针
			
			byte[] bytes = new byte[1024];
			
			int count = 0;
			
			while((count = raf.read(bytes))!=-1) {
				
				fo.write(bytes,0,count);
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	public static void copy(String source,String target) {
		
		try(
			FileInputStream fi = new FileInputStream(source);
			FileOutputStream fo = new FileOutputStream(target);	
		) {
			
			byte[] bytes = new byte[1024];
			int count = 0;
			
			//文件大小
			File f = new File(source);
			
			long size = f.length();
			long ran = (long)(Math.random()*size);
			
			
			long sum = 0;
			while((count = fi.read(bytes)) != -1) {
				
				sum+=count;
				
				if(sum>=ran) break;
				
				fo.write(bytes,0,count);
				
			}
			
			System.out.println("文件大小"+size);
			System.out.println("复制停止:"+ran);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

}
